package com.icoolkj.security.springboot.service;

import com.icoolkj.security.springboot.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2025/02/07 12:37
 */
@Service
public class SpringDataUserDetailsService implements UserDetailsService {

    @Autowired
    private IUserService userService;

    // 根据账号查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 将来连接数据库根据账号查询用户信息
        UserDTO user = userService.getUserByUserName(username);
        if (user == null){
            // 如果用户查询不到，返回 null，由 provider 来抛出异常
            return null;
        }
        // 暂时采用模拟方式

        // 登录账号
        System.out.println("username ==>" +username);

        // 暂时采用模拟方式
        UserDetails userDetails = User.withUsername(user.getUsername()).password(user.getPassword()).authorities("p1").build();

        return userDetails;
    }
}
